#include <common.h>

#if defined(MULTIPROGRAM) && !defined(TIME_SHARING)
# define MULTIPROGRAM_YIELD() yield()
#else
# define MULTIPROGRAM_YIELD()
#endif

#define NAME(key) \
  [AM_KEY_##key] = #key,

static const char *keyname[256] __attribute__((used)) = {
  [AM_KEY_NONE] = "NONE",
  AM_KEYS(NAME)
};

size_t serial_write(const void *buf, size_t offset, size_t len) {
	for(size_t i =0;i<len;i++){
		putch(*(char*)(buf+i));
	}
  return len;
}

int int_to_string(int n, char *buf1);
size_t events_read(void *buf, size_t offset, size_t len) {
	AM_INPUT_KEYBRD_T ev = io_read(AM_INPUT_KEYBRD);
	if(ev.keycode == AM_KEY_NONE) return 0;
	if(ev.keydown)strcpy(buf,"kd:");
	else strcpy(buf,"ku:");
	assert(len>3+strlen(keyname[ev.keycode]+1));
	strcat(buf,keyname[ev.keycode]);
	strcat(buf," keycode:");
	char buf1[64] = {};
	int_to_string(ev.keycode,buf1);
	strcat(buf,buf1);
	return strlen(buf);
}

int int_to_string(int n, char*buf1);
size_t dispinfo_read(void *buf, size_t offset, size_t len) {
	int  width = io_read(AM_GPU_CONFIG).width;
	int  high = io_read(AM_GPU_CONFIG).height;
	char file[64]={};
	char width_buf[32]={};
	char high_buf[32] = {};
	strcpy(file,"WIDTH:");
	int len_w =int_to_string(width,width_buf);
	int len_h =int_to_string(high,high_buf);
	assert(len_w+len_h+6+8<64);
	strcat(file,width_buf);
	strcat(file," HEIGHT:");
	strcat(file,high_buf);
	strcpy(buf,file);
  return len;
} 
size_t fb_write(const void *buf, size_t offset, size_t len) {
//	int w = len&0xffff;
//	int h = (len >> 16)&0xffff;	
//	int x = offset % io_read(AM_GPU_CONFIG).width;
//	int y = offset /io_read(AM_GPU_CONFIG).height;
//	io_write(AM_GPU_FBDRAW,x,y,buf,w,h,true);
	uint32_t *fb = (uint32_t*)0xa1000000;
	memcpy(fb+offset,buf,len);	
	io_write(AM_GPU_FBDRAW,0,0,NULL,0,0,true);
  return 0;
}

void init_device() {
  Log("Initializing devices...");
  ioe_init();
}
